﻿Imports System.Data
Imports ADOEntityKYC

Partial Class Administrator_frmReviewRiskPeriod
    Inherits Web.UI.BasePage
    Private Const strMenuCode As String = "M71"
    Dim sRiskEntity As RiskEntities
    Dim dzRisk As New DataSet
    Dim clsQuery As clsDatabase
    Dim clsDataTable As New clsLINQToDataTable
    Dim intBeforeItemIndex As Integer
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim strMsg As String = ""
    Dim clsMasterDropDown As clsMasterDropDown

#Region " Even Page "
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        btnSearch.Text = Resources.resButton.btnSearch
        btnAdd.Text = Resources.resButton.btnAdd
        btnModify.Text = Resources.resButton.btnModify
        btnDelete.Text = Resources.resButton.btnDelete
        btnClear.Text = Resources.resButton.btnClear

        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            clsMasterDropDown = New clsMasterDropDown
            sRiskEntity = New RiskEntities
            clsSessionMenuRight = Session("clsMenuRight")

            If (Not IsPostBack) Then
                CreateControlMP()
                setButton(1)
                setUserRightButton()
            Else
                dzRisk = Session("dsTblMaster")
                gvData.DataSource = dzRisk.Tables("sPeriod")
                gvData.DataBind()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('เกิดข้อผิดพลาดในการโหลด')", True)
        End Try


    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dzRisk
    End Sub

#End Region

#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "ข้อมูลหลัก > KYC > ช่วงเวลาทบทวนความเสี่ยง"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        IsDataBind()
        clearGvIndex()
        SaveLogSearch()

    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Try
            If chkBeforeSave() Then
                sRiskEntity = New RiskEntities
                Dim sPeriod As New REVIEW_RISK_PERIOD

                sPeriod.RISK_LEVEL = ddlRiskLevel.SelectedValue
                sPeriod.REVIEW_PERIOD = txtPeriod.Text
                sPeriod.CREATEBY = clsSessionMenuRight.getUserName
                sPeriod.CREATEDATE = DateTime.Now


                sRiskEntity.AddToREVIEW_RISK_PERIOD(sPeriod)
                sRiskEntity.SaveChanges()

                SaveLogNew()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)

            End If
        Catch ex As System.Data.UpdateException

            Dim codeError() As String = ex.InnerException.Message.Split(":")
            If codeError(0) = "ORA-00001" Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถเพิ่มได้ เนื่องจากรหัสนี้มีการนำมาใช้ในระบบแล้ว')", True)
            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            End If
            WriteError(ex, "btnAdd_Click", "frmReviewRiskPeriod")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnAdd_Click", "frmReviewRiskPeriod")
        End Try
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click



        Try
            If chkBeforeSave() Then
                sRiskEntity = New RiskEntities
                Dim sPeriod As New REVIEW_RISK_PERIOD

                Dim qry = (From t In sRiskEntity.REVIEW_RISK_PERIOD Where t.RISK_LEVEL = ddlRiskLevel.SelectedValue).ToList
                qry(0).REVIEW_PERIOD = txtPeriod.Text
                qry(0).UPDATEBY = clsSessionMenuRight.getUserName
                qry(0).UPDATEDATE = DateTime.Now

                sRiskEntity.SaveChanges()

                SaveLogEdit()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)
            End If

        Catch ex As System.Data.UpdateException
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            WriteError(ex, "btnModify_Click", "frmReviewRiskPeriod")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnModify_Click", "frmReviewRiskPeriod")
        End Try


    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Not (gvData.SelectedIndex = -1) Then
            Dim level As String = gvData.Rows(gvData.SelectedIndex).Cells(1).Text
            Try
                sRiskEntity = New RiskEntities
                Dim qry = (From t In sRiskEntity.REVIEW_RISK_PERIOD Where t.RISK_LEVEL = level).ToList
                sRiskEntity.DeleteObject(qry(0))
                sRiskEntity.SaveChanges()

                SaveLogDelete(level)

                IsDataBind()
                reset()

            Catch ex As System.Data.UpdateException
                Dim codeError() As String = ex.InnerException.Message.Split(":")
                If codeError(0) = "ORA-02292" Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
                Else
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
                End If
                WriteError(ex, "btnDelete_Click", "frmReviewRiskPeriod")
            Catch ex As Exception
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)
                WriteError(ex, "btnDelete_Click", "frmReviewRiskPeriod")
            End Try

        Else
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If

    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        clear()
    End Sub

#End Region

#Region "Even GridView"

    Protected Sub gvData_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvData.SelectedIndexChanged

        If (gvData.SelectedIndex = intBeforeItemIndex) Then
            clearGvIndex()
            reset()
            btnModify.Text = "แก้ไข"
        Else
            btnModify.Text = "บันทึก"

            setButton(2)

            txtPeriod.Text = gvData.Rows(gvData.SelectedIndex).Cells(2).Text
            ddlRiskLevel.SelectedValue = gvData.Rows(gvData.SelectedIndex).Cells(1).Text

            btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                       IIf(gvData.SelectedIndex = -1, "", gvData.Rows(gvData.SelectedIndex).Cells(1).Text)) + "');")

        End If
    End Sub
    Protected Sub gvData_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles gvData.SelectedIndexChanging
        intBeforeItemIndex = gvData.SelectedIndex
    End Sub

    Protected Sub gvData_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvData.PageIndexChanging
        Try
            gvData.PageIndex = e.NewPageIndex
            clearGvIndex()
            DataBind()
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub gvData_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvData.Sorting
        Dim dt = TryCast(dzRisk.Tables("sPeriod"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            gvData.DataSource = dzRisk.Tables("sPeriod")
            gvData.DataBind()
            clearGvIndex()
        End If
    End Sub

#End Region

#Region " Function"

    Private Sub setUserRightButton()
        Try
            Dim col As New Collection
            col.Add(btnSearch, statusbtn.Query.ToString)
            col.Add(btnAdd, statusbtn.Add.ToString)
            col.Add(btnModify, statusbtn.Modify.ToString)
            col.Add(btnDelete, statusbtn.delete.ToString)
            setBtnToUserRight(col, strMenuCode, clsSessionMenuRight.getDsMenuRight)
        Catch ex As Exception
            Throw ex
            WriteError(ex, "setUserRightButton", "frmReviewRiskPeriod")
        End Try
    End Sub

    Private Sub clearGvIndex()
        gvData.SelectedIndex = -1
        '  btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()
        Try

            sRiskEntity = New RiskEntities

            If dzRisk.Tables.Contains("sPeriod") Then
                dzRisk.Tables.Clear()
            End If

            Dim qry = From t In sRiskEntity.REVIEW_RISK_PERIOD
                        Order By t.RISK_LEVEL
                    Select t.RISK_LEVEL, t.REVIEW_PERIOD

            If Not (txtPeriod.Text = "") Then
                qry = qry.Where(Function(t) t.REVIEW_PERIOD = txtPeriod.Text)
            End If

            If Not (ddlRiskLevel.SelectedValue = "") Then
                qry = qry.Where(Function(t) t.RISK_LEVEL = ddlRiskLevel.SelectedValue)
            End If

            dzRisk.Tables.Add(clsDataTable.LINQToDataTable(qry, "sPeriod").Copy)

            If (qry.Count = 0) Then
                lblMsg.Visible = True
                lblTotal.Text = ""
            Else
                lblMsg.Visible = False
                lblTotal.Text = "จำนวนรายการทั้งหมด " + qry.Count.ToString + " รายการ "

            End If

            gvData.DataSource = dzRisk.Tables("sPeriod")
            gvData.DataBind()

            clsDataTable = Nothing
        Catch ex As Exception
            WriteError(ex, "IsDataBind", "frmReviewRiskPeriod")
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + "เกิดข้อผิดพลาดในการโหลด" + "')", True)

        End Try
    End Sub

    Private Function GetSortDirection(ByVal column As String) As String
        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"
        Try
            ' Retrieve the last column that was sorted.
            Dim sortExpression = TryCast(ViewState("SortExpression"), String)

            If sortExpression IsNot Nothing Then
                ' Check if the same column is being sorted.
                ' Otherwise, the default value can be returned.
                If sortExpression = column Then
                    Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                    If lastDirection IsNot Nothing _
                      AndAlso lastDirection = "DESC" Then

                        sortDirection = "ASC"

                    End If
                End If
            End If

            ' Save new values in ViewState.
            ViewState("SortDirection") = sortDirection
            ViewState("SortExpression") = column
        Catch ex As Exception
            WriteError(ex, "GetSortDirection", "frmReviewRiskPeriod")
        End Try

        Return sortDirection
    End Function

    Private Sub setButton(ByVal button As Integer)

        If button = 1 Then 'unselect
            lblMsg.Visible = False

            btnModify.Enabled = False
            btnDelete.Enabled = False

            btnSearch.Enabled = True
            btnAdd.Enabled = True

            ddlRiskLevel.Enabled = True

        ElseIf button = 2 Then 'select

            btnSearch.Enabled = False
            btnAdd.Enabled = False

            btnModify.Enabled = True
            btnDelete.Enabled = True

            ddlRiskLevel.Enabled = False

        End If

    End Sub

    Private Sub clear()
        If (dzRisk.Tables.Contains("sPeriod")) Then
            dzRisk.Tables("sPeriod").Clear()
            gvData.DataSource = dzRisk.Tables("sPeriod")
            gvData.DataBind()
        End If
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        ddlRiskLevel.SelectedValue = ""
        txtPeriod.Text = ""
        lblTotal.Text = ""
        btnModify.Text = "แก้ไข"
    End Sub

    Private Sub reset()
        'gvUserRight.DataSource = dsUserRight.Tables("sUserRight")
        'gvUserRight.DataBind()
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        ddlRiskLevel.SelectedValue = ""
        txtPeriod.Text = ""
    End Sub

    Private Function chkBeforeSave() As Boolean
        Dim result As Boolean = True

        If (ddlRiskLevel.SelectedValue = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุระดับความเสี่ยง" & "\n"
        End If

        If (txtPeriod.Text = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุระยะเวลาทบทวนความเสี่ยง" & "\n"
        End If

        Return result

    End Function

    Private Sub SaveLogSearch()
        Try

            Dim desc As String = ""

            If Not (ddlRiskLevel.SelectedValue = "") Then
                desc += " ระดับความเสี่ยง - " + ddlRiskLevel.SelectedItem.Text
            End If

            If Not (txtPeriod.Text = "") Then
                desc += " ระยะเวลาทบทวน - " + txtPeriod.Text
            End If

            If Not desc = "" Then
                desc = "ค้นหาข้อมูลเขต จาก " + desc
            Else
                desc = "ค้นหาทั้งหมด"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 1, desc, "M63")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogPrint()
        Try

            Dim desc As String = "พิมพ์ข้อมูลเขต"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 2, desc, "M63")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogNew()
        Try

            Dim desc As String = "บันทึก ข้อมูลระยะเวลาทบทวนความเสี่ยง (ระดับ " + ddlRiskLevel.SelectedValue + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(ddlRiskLevel.SelectedValue, clsSessionMenuRight.getUserName, 3, desc, "M71")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogEdit()
        Try

            Dim desc As String = "บันทึก แก้ไข ข้อมูลระยะเวลาทบทวนความเสี่ยง (ระดับ " + ddlRiskLevel.SelectedValue + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(ddlRiskLevel.SelectedValue, clsSessionMenuRight.getUserName, 4, desc, "M71")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogDelete(ByVal value As String)
        Try

            Dim desc As String = "ลบข้อมูลระยะเวลาทบทวนความเสี่ยง (ระดับ " + value + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(value, clsSessionMenuRight.getUserName, 5, desc, "M71")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region



End Class
